<template>
  <div class="user-profile">
    <div class="container">
      <h1 class="page-title">个人资料</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <template v-else-if="currentUser">
        <el-row :gutter="20">
          <el-col :md="8" :xs="24">
            <div class="profile-card">
              <div class="avatar-container">
                <img :src="avatarUrl" :alt="currentUser.username || '用户头像'" class="avatar">
                <div class="edit-avatar">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-camera"></i>
                  </el-upload>
                </div>
              </div>
              <h3 class="username">{{ currentUser.username || '未设置用户名' }}</h3>
              <div class="user-role">
                <el-tag type="success" v-if="isAdmin">管理员</el-tag>
                <el-tag type="info" v-else>普通用户</el-tag>
              </div>
              <div class="user-info">
                <div class="info-item">
                  <i class="el-icon-time"></i>
                  <span>注册时间：{{ formatDate(currentUser.created_at) }}</span>
                </div>
              </div>
              
              <div class="profile-nav">
                <div 
                  class="nav-item" 
                  :class="{ active: activeTab === 'profile' }"
                  @click="activeTab = 'profile'"
                >
                  <i class="el-icon-user"></i>
                  <span>基本资料</span>
                </div>
                <div 
                  class="nav-item" 
                  :class="{ active: activeTab === 'security' }"
                  @click="activeTab = 'security'"
                >
                  <i class="el-icon-lock"></i>
                  <span>安全设置</span>
                </div>
              </div>
            </div>
          </el-col>
          
          <el-col :md="16" :xs="24">
            <div class="profile-content">
              <div v-if="activeTab === 'profile'">
                <div class="section-title">
                  <h2>基本资料</h2>
                  <p>您可以在此更新个人信息</p>
                </div>
                
                <el-form 
                  ref="profileForm" 
                  :model="profileData" 
                  :rules="profileRules" 
                  label-position="top"
                >
                  <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                      <el-form-item label="昵称" prop="username">
                        <el-input v-model="profileData.username" placeholder="请输入昵称" />
                      </el-form-item>
                    </el-col>
                    
                    <el-col :md="12" :xs="24">
                      <el-form-item label="真实姓名" prop="full_name">
                        <el-input v-model="profileData.full_name" placeholder="请输入真实姓名" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                      <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model="profileData.email" placeholder="请输入电子邮箱" />
                      </el-form-item>
                    </el-col>
                    
                    <el-col :md="12" :xs="24">
                      <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="profileData.phone" placeholder="请输入手机号码" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-form-item label="所在地区" prop="address">
                    <el-cascader
                      v-model="profileData.address"
                      :options="regionOptions"
                      placeholder="请选择所在地区"
                      style="width: 100%"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="updateProfile"
                      :loading="updatingProfile"
                    >
                      保存修改
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <div v-else-if="activeTab === 'security'">
                <div class="section-title">
                  <h2>安全设置</h2>
                  <p>您可以在此修改密码等安全相关设置</p>
                </div>
                
                <el-form 
                  ref="passwordForm" 
                  :model="passwordData" 
                  :rules="passwordRules" 
                  label-position="top"
                >
                  <el-form-item label="当前密码" prop="currentPassword">
                    <el-input 
                      v-model="passwordData.currentPassword" 
                      type="password" 
                      placeholder="请输入当前密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordData.newPassword" 
                      type="password" 
                      placeholder="请输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordData.confirmPassword" 
                      type="password" 
                      placeholder="请再次输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="changePassword"
                      :loading="changingPassword"
                    >
                      修改密码
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-result
          icon="warning"
          title="访问受限"
          sub-title="请先登录后再访问此页面"
        >
          <template #extra>
            <el-button type="primary" @click="$router.push('/login')">
              去登录
            </el-button>
          </template>
        </el-result>
      </template>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios';
import bcrypt from 'bcryptjs';

export default {
  name: 'UserProfile',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordData.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      activeTab: 'profile',
      updatingProfile: false,
      changingPassword: false,
      
      profileData: {
        username: '',
        email: '',
        full_name: '',
        phone: '',
        address: '',
        is_admin: 0
      },
      
      passwordData: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      profileRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        full_name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
          { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
          { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
        ]
      },
      
      passwordRules: {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value === this.passwordData.currentPassword) {
                callback(new Error('新密码不能与当前密码相同'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      
      regionOptions: [
        {
          value: 'beijing',
          label: '北京',
          children: [
            { value: 'chaoyang', label: '朝阳区' },
            { value: 'haidian', label: '海淀区' },
            { value: 'dongcheng', label: '东城区' },
            { value: 'xicheng', label: '西城区' },
            { value: 'fengtai', label: '丰台区' },
            { value: 'shijingshan', label: '石景山区' }
          ]
        },
        {
          value: 'shanghai',
          label: '上海',
          children: [
            { value: 'pudong', label: '浦东新区' },
            { value: 'huangpu', label: '黄浦区' },
            { value: 'jing_an', label: '静安区' },
            { value: 'xuhui', label: '徐汇区' },
            { value: 'changning', label: '长宁区' },
            { value: 'putuo', label: '普陀区' }
          ]
        },
        {
          value: 'guangzhou',
          label: '广州',
          children: [
            { value: 'tianhe', label: '天河区' },
            { value: 'yuexiu', label: '越秀区' },
            { value: 'liwan', label: '荔湾区' },
            { value: 'haizhu', label: '海珠区' }
          ]
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      currentUser: 'auth/currentUser',
      isAdmin: 'auth/isAdmin',
      loading: 'isLoading'
    }),
    avatarUrl() {
      if (!this.currentUser) {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
      }
      return this.currentUser.avatar_url 
        ? `${process.env.VUE_APP_API_URL}${this.currentUser.avatar_url}`
        : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
    }
  },
  watch: {
    currentUser: {
      handler: 'initProfileData',
      immediate: true // Make sure to call the handler immediately if currentUser already has a value
    }
  },
  created() {
    // 初始化表单数据
    this.initProfileData();
  },
  methods: {
    ...mapActions({
      updateProfileAction: 'auth/updateProfile',
      changePasswordAction: 'auth/changePassword'
    }),
    initProfileData() {
      const user = this.currentUser;
      if (user) {
        console.log('初始化用户数据:', user);
        this.profileData = {
          username: user.username || '',
          email: user.email || '',
          full_name: user.full_name || '',
          phone: user.phone || '',
          address: user.address || '',
          is_admin: user.is_admin || 0,
          created_at: user.created_at,
          updated_at: user.updated_at
        };
        console.log('初始化后的表单数据:', this.profileData);
      }
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!');
        return false;
      }
      
      // 这里应该上传头像，但由于没有实际的后端，我们只是显示一条成功消息
      this.$message.success('头像上传成功！');
      return false; // 阻止默认上传行为
    },
    async updateProfile() {
      try {
        // 表单验证
        await this.$refs.profileForm.validate();
        
        this.updatingProfile = true;
        
        // 构造符合数据库字段的数据
        const userData = {
          id: this.currentUser.id, // 保持用户ID
          username: this.profileData.username,
          email: this.profileData.email,
          full_name: this.profileData.full_name,
          phone: this.profileData.phone || '',
          address: typeof this.profileData.address === 'object' ? 
            (Array.isArray(this.profileData.address) ? this.profileData.address.join('/') : '') : 
            (this.profileData.address || ''),
          is_admin: this.currentUser.is_admin, // 保持管理员状态不变
          created_at: this.currentUser.created_at, // 保持创建时间不变
          updated_at: new Date().toISOString() // 更新修改时间为当前时间
        };

        // 打印要提交的数据
        console.log('准备提交的用户数据:', userData);

        try {
          const response = await axios({
            method: 'put',
            url: 'http://localhost:3000/api/users/profile',
            data: userData,
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
          });

          console.log('服务器响应:', response);

          if (response.data && response.data.code === 200) {
            // 更新 Vuex store
            await this.updateProfileAction(userData);
            
            this.$message.success('个人资料更新成功');
            
            // 重新获取用户信息
            await this.initProfileData();
          } else {
            throw new Error(response.data?.message || '更新失败');
          }
        } catch (error) {
          console.error('更新个人资料失败:', error);
          if (error.response) {
            console.error('错误响应:', error.response.data);
            this.$message.error(error.response.data?.message || '更新失败，请稍后重试');
          } else {
            this.$message.error('网络错误，请稍后重试');
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error);
        this.$message.error('请检查表单填写是否正确');
      } finally {
        this.updatingProfile = false;
      }
    },
    async changePassword() {
      if (this.changingPassword) return;

      try {
        // 表单验证
        await this.$refs.passwordForm.validate();
        
        this.changingPassword = true;
        
        try {
          const response = await axios({
            method: 'put',
            url: '/api/users/password',
            data: {
          current_password: this.passwordData.currentPassword,
          new_password: this.passwordData.newPassword
            },
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
        
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '密码修改成功，请重新登录',
            type: 'success',
              duration: 3000
          });
          
            // 重置表单
          this.passwordData = {
            currentPassword: '',
            newPassword: '',
            confirmPassword: ''
          };
          this.$refs.passwordForm.resetFields();

            // 立即清除用户数据
            await this.$store.dispatch('auth/logout');
            
            // 立即跳转到登录页面
            this.$router.push({
              path: '/login',
              query: { 
                message: '密码已修改，请使用新密码登录'
              }
            });
        }
      } catch (error) {
          console.error('密码修改失败:', error);
          
          let errorMessage = '密码修改失败，请稍后重试';
          if (error.response) {
            switch (error.response.status) {
              case 400:
                errorMessage = error.response.data.message || '请检查密码格式';
                break;
              case 401:
                errorMessage = '当前密码不正确';
                break;
              case 404:
                errorMessage = '用户不存在';
                break;
              default:
                errorMessage = error.response.data.message || '服务器错误，请稍后重试';
            }
          }

          this.$notify({
            title: '错误',
            message: errorMessage,
            type: 'error',
            duration: 4000
          });
        }
      } catch (validationError) {
        this.$notify({
          title: '提示',
          message: '请检查输入是否正确',
          type: 'warning',
          duration: 3000
        });
      } finally {
        this.changingPassword = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.user-profile {
  padding: 40px 0;
}

.loading-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.profile-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.edit-avatar {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  
  &:hover {
    background-color: color.adjust(#42b983, $lightness: -10%);
  }
  
  .el-icon-camera {
    font-size: 16px;
  }
}

.username {
  font-size: 1.5rem;
  margin-bottom: 10px;
  color: var(--secondary-color);
}

.user-role {
  margin-bottom: 20px;
}

.user-info {
  text-align: left;
  margin-bottom: 20px;
  
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: var(--gray-color);
    
    i {
      margin-right: 10px;
    }
  }
}

.profile-nav {
  border-top: 1px solid #eee;
  padding-top: 20px;
  
  .nav-item {
    display: flex;
    align-items: center;
    padding: 10px;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    
    i {
      margin-right: 10px;
    }
    
    &:hover {
      background-color: #f5f7fa;
    }
    
    &.active {
      background-color: #ecf5ff;
      color: var(--primary-color);
    }
  }
}

.profile-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.section-title {
  margin-bottom: 20px;
  
  h2 {
    margin-bottom: 5px;
    color: var(--secondary-color);
  }
  
  p {
    color: var(--gray-color);
    font-size: 0.9rem;
  }
}

@media (max-width: 768px) {
  .profile-card {
    margin-bottom: 20px;
  }
}
</style> 